package com.yaosheng.thread.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Created by yaosheng on 2021/7/1.
 */
public class Test03 {

    volatile List lists = new ArrayList ();

    public void add(Object o){
        lists.add (o);
    }

    public int size(){
        return lists.size ();
    }

    public static void main(String[] args) {

        Test03 test03 = new Test03 ();
        CountDownLatch latch = new CountDownLatch (5);

        new Thread ( () -> {

                System.out.println ("t2启动");
                if(test03.size () != 5){
                    try{
                        latch.await ();
                    } catch (InterruptedException e) {
                        e.printStackTrace ();
                    }
                }
                System.out.println ("t2结束");

        },"t2").start ();

        try{
            TimeUnit.SECONDS.sleep (1);
        }catch (InterruptedException e){
            e.printStackTrace ();
        }

        new Thread ( () -> {

                System.out.println ("t1启动");
                for(int i = 0;i < 10;i ++){
                    test03.add (new Object ());
                    System.out.println ("add" + i);
                    if(test03.size () != 5){
                        latch.countDown ();
                    }
                    try{
                        TimeUnit.SECONDS.sleep (1);
                    }catch (InterruptedException e){
                        e.printStackTrace ();
                    }
                }
        },"t1").start ();
    }
}
